﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Telerik.Web.UI;
using Company.Merchandising.BusinessLayer.DataTransferObjects;

namespace Company.Merchandising.ServiceLayer.MenuManagement
{
    public static class MenuAuthorizationManager
    {
        private const string REQUIRED_FACULTY_ATTRIBUTE_NAME = "requiredFaculty";
        private static char[] FACULITIES_SEPARATORS = new char[] { ';' };

        public static void AuthorizeMenu(RadMenu menuObject, List<DTOFaculty> ownedFaculties)
        {
            foreach (RadMenuItem menuItem in menuObject.Items)
            {
                AuthorizeSingleMenuItem(menuItem, ownedFaculties);
            }
        }

        private static void AuthorizeSingleMenuItem(RadMenuItem menuItem, List<DTOFaculty> ownedFaculties)
        {
            if (!CheckIfAllowedMenuItem(menuItem, ownedFaculties))
            {
                menuItem.Remove();
                return;
            }

            foreach (RadMenuItem subMenuItem in menuItem.Items)
            {
                AuthorizeSingleMenuItem(subMenuItem, ownedFaculties);
            }
        }

        private static bool CheckIfAllowedMenuItem(RadMenuItem menuItem, List<DTOFaculty> ownedFaculties)
        {
            List<string> requiredFaculties = menuItem.Attributes[REQUIRED_FACULTY_ATTRIBUTE_NAME].Split(FACULITIES_SEPARATORS, StringSplitOptions.RemoveEmptyEntries).ToList<string>();
            return requiredFaculties.TrueForAll(requiredFaculty => ownedFaculties.Exists(ownedFaculty => ownedFaculty.Name.Equals(requiredFaculty, StringComparison.OrdinalIgnoreCase)));
        }
    }
}
